
"""
------------------------------------------------------------------------------
Copyright (C) 2007 Zeb.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
A tool generate python export code from C++ header file.

How to use:
    1).Add python configure code to C++ header file, for example:
    #if 0
    ++-- begin export py interface --++
        EXPORT_CONFIG = {
            'namespace' : 'MK3DE',
            'type' : 'singleton',
            'singleton' : 'GetEngine()->GetSceneManager()->',
            'method prefix' : 'SM_',
            'method list' : 
            '''
                CSceneNode* AddSceneNode(CSceneNode* pParent, SCENE_NODE_TYPE type);
                BOOL RemoveSceneNode(/* inout */ CSceneNode** pSceneNode);
            ''',
            'py output file' : 'py_scene_manager',
            'module name' : 'SCENE_MANAGER',
        }
    ++-- end export py interface --++
    #endif
        
    2).Run cpp2py.

 
author: Zeb(mailto:zebbey@gmail.com)
date: 2007-6-16
"""

import cppparser

BEGIN_EXPORT = '++-- begin export py interface --++'
END_EXPORT = '++-- end export py interface --++'

def getConfigCodeList(fileName):
    hfile = open(fileName)
    ret = []
    while True:
        line = hfile.readline()
        if not line:
            break
        
        code = ''
        line = line.strip()
        if line == BEGIN_EXPORT:
            while True:
                l = hfile.readline()
                if not l:
                    return []
                
                l = l.strip()
                if l == END_EXPORT:
                    break
                
                code += l
                
            ret.append(code)
                
    return ret

if __name__ == '__main__':
    import sys
    import os
    import fnmatch
    
    if len(sys.argv) < 5:
        print 'Usage: cpp2py <cpp header directory path> <output directory> <configure file> <module name>'
        sys.exit(0)
    
    try:
        mod_inline = set()
        mod_inc_list = []
        mod_api_list = []
        mod_con_list = []
        filelist = os.listdir(sys.argv[1])
        for f in filelist:
            if os.path.isfile('%s\\%s' % (sys.argv[1], f)) and fnmatch.fnmatch(f, '*.%s' % cppparser.INTERFACE_EXT):
                codeList = getConfigCodeList('%s\\%s' % (sys.argv[1], f))
                for code in codeList:
                    exec(code)

                    cppparser.cppParser.parse(EXPORT_CONFIG, sys.argv[2], mod_inline, mod_inc_list, mod_api_list, mod_con_list)
                    print 'Transform %s ok.' % f

        mainFile = open('%s.python.cpp' % sys.argv[4], 'w')
        mainFile.write('/* this is automatic generated by cpp2py, do not modifiy it manually. */\n')
        mainFile.writelines(mod_inline)
        mainFile.writelines(map(lambda n : '#include "%s.h"\n' % n, mod_inc_list))        
        mainFile.write('\n')
        mainFile.write('extern "C" __declspec(dllexport) void init%s()\n{\n' % sys.argv[4])
        mainFile.writelines(map(lambda n : '\tPy_InitModule("%s", %s);\n' % (n[0], n[1]), mod_api_list))
        mainFile.writelines(map(lambda n : '\t%s\n' % n, mod_con_list))
        mainFile.write('}\n')
        mainFile.close()
                   
    except:
        import traceback
        import StringIO
        import sys
        
        excinfo = sys.exc_info()
        sio = StringIO.StringIO()
        traceback.print_exception(excinfo[0], excinfo[1], excinfo[2], None, sio)
        s = sio.getvalue()
        print traceback.format_exc()
        sio.close()        

    print 'Press enter to exit...'
    raw_input()


